import Taro from "@tarojs/taro";

/**
 * 检查并请求Wi-Fi权限
 * @returns 是否已授权
 */
export const checkWifiAuth = async (): Promise<boolean> => {
  try {
    // 1. 检查当前权限状态
    const authSetting = await Taro.getSetting();
    if (authSetting.authSetting?.["scope.userLocation"]) {
      return true;
    }

    // 2. 请求权限
    await Taro.authorize({ scope: "scope.userLocation" });
    return true;
  } catch (error) {
    console.error("Wi-Fi授权失败:", error);
    await Taro.showModal({
      title: "提示",
      content: "需要Wi-Fi权限才能获取网络信息",
      confirmText: "去设置",
      success: res => {
        if (res.confirm) {
          Taro.openSetting(); // 跳转设置页
        }
      },
    });
    return false;
  }
};

/**
 * 获取当前连接的Wi-Fi信息
 */
// export const getConnectedWifiInfo = async () => {
//   const hasAuth = await checkWifiAuth();
//   if (!hasAuth) return null;
//   Taro.startWifi({
//     success: async function (res) {
//       try {
//         const res = await Taro.getConnectedWifi();
//         return {
//           ssid: res.wifi?.SSID,
//           bssid: res.wifi?.BSSID,
//           secure: res.wifi?.secure,
//           signalStrength: res.wifi?.signalStrength,
//         };
//       } catch (error) {
//         console.error("获取Wi-Fi信息失败666:", error);
//         return null;
//       }
//     },
//     fail: function (err) {
//       console.log(err, "err6669");
//     },
//   });
// };
// 检查并请求位置授权
export const checkLocationAuth = () => {
  return new Promise((resolve, reject) => {
    // 1. 检查是否已有授权
    (wx as unknown as wx).getSetting({
      success(res) {
        if (res.authSetting["scope.userLocation"] === false) {
          // 2. 已拒绝过授权，引导用户手动开启
          (wx as unknown as wx).showModal({
            title: "位置授权提示",
            content: "需要位置权限才能获取当前位置，是否去设置开启？",
            success(res) {
              if (res.confirm) {
                (wx as unknown as wx).openSetting({
                  success(settingRes) {
                    if (settingRes.authSetting["scope.userLocation"]) {
                      resolve(true); // 用户已授权
                    } else {
                      reject(new Error("用户拒绝授权"));
                    }
                  },
                });
              }
            },
          });
        } else if (res.authSetting["scope.userLocation"] === undefined) {
          // 3. 首次请求授权
          (wx as unknown as wx).authorize({
            scope: "scope.userLocation",
            success() {
              resolve(true); // 用户已授权
            },
            fail() {
              reject(new Error("用户拒绝授权"));
            },
          });
        } else {
          // 已有授权
          resolve(true);
        }
      },
      fail(err) {
        reject(err);
      },
    });
  });
};
// 获取当前位置
export const getCurrentLocation = ()=> {
  return new Promise((resolve, reject) => {
    checkLocationAuth()
      .then(() => {
        (wx as unknown as wx).getLocation({
          type: 'wgs84',
          altitude: true,
          success(res) {
            resolve({
              longitude: res.longitude,
              latitude: res.latitude,
              altitude: res.altitude,
              speed: res.speed
            });
          },
          fail(err) {
            reject(err);
          }
        });
      })
      .catch(err => {
        reject(err);
      });
  });
}
